<?php
/**
 * nonce.class
 *
 * Nonces
 *
 * @version:	1.0
 * @package:	core
 * @author:	and (http://codeispoetry.ru)
 * @created:	Wed Jan 13 20:05:35 MSK 2010
 *
 * @copyright:	(c) 2010 alex <qfox@ya.ru> yaroshevich aka alex_ez. All rights reserved.
 */

class nonce extends singleton
{
    static public function &instance() { 
        return parent::instance(__CLASS__);
    }

    protected $nonce_field = '_nonce';
    protected $salt = '';

    public function __construct()
    {
        $nonce_secret = '';
        $nonce_field = '';

        $hash = config::instance()->hash;

        if(is_array($hash))
            extract($hash);

        if(empty($nonce_secret))
            $nonce_secret = config::instance()->db_url;

        if(!empty($nonce_field))
            $this->nonce_field = $nonce_field;

        $this->salt = $nonce_secret;
    }

    public function get_nonce_field() {
        return $this->nonce_field;
    }

    public function check_nonce($action = -1, $nonce = false)
    {
        $request = Request::instance();
        $request_nonce = $request->r($this->nonce_field);

        if(empty($nonce) && !empty($request_nonce)) {
            $nonce = $request_nonce;
        }

        $valid_nonce = $this->create_nonce($action);

        if($valid_nonce == $nonce) {
            return true;
        }

        return false;
    }

    public function create_nonce($action = -1)
    {
        $uid = (int)visitor::instance()->user_id();
        $i = ceil(time() / 43200);

        return substr($this->create_hash($i . $action . $uid), -12, 10);
    }

    public function create_hash($data) {
        if ( function_exists('hash_hmac') ) {
            return hash_hmac('md5', $data, $this->salt);
        } else {
            return md5($data . $this->salt);
        }
    }
}
?>
